package com.cloudeye.logtest.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.net.SocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * Created by lafangyuan on 2020/12/31.
 */
@Slf4j
public class ConnectClientHandler extends ChannelInboundHandlerAdapter {

    private HeartbeatClient client;

    public ConnectClientHandler(HeartbeatClient client) {
        this.client = client;
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent) evt;
            if(event.state().equals(IdleState.WRITER_IDLE)){
                log.info("di di di ...");
                ctx.writeAndFlush("di di di ...");
            }
        }else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("服务器断开连接，正在重试2...");
        final EventLoop eventLoop = ctx.channel().eventLoop();
        eventLoop.schedule(
                ()->{
                    client.connect(new Bootstrap(),eventLoop);
                },5L, TimeUnit.SECONDS
        );
        super.exceptionCaught(ctx, cause);
    }
}
